package pri.syl.xiaowu.websocket.core.template;

import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.CharsetUtil;
import lombok.Data;

/**
 * @Author YunLong
 * @Date 2021/7/18 18:09
 * @Description WebsocketChannel方法模板
 **/
@Data
public class WebsocketChannelTemplate {
    private Channel channel;

    public WebsocketChannelTemplate(Channel channel) {
        this.channel = channel;
    }

    public void pingMessage() {
        channel.writeAndFlush(new PingWebSocketFrame());
    }

    public void pingMessage(String message) {
        channel.writeAndFlush(new PingWebSocketFrame(Unpooled.copiedBuffer(message, CharsetUtil.UTF_8)));
    }

    public void pingMessage(byte[] message) {
        channel.writeAndFlush(new PingWebSocketFrame(Unpooled.copiedBuffer(message)));
    }

    public void pongMessage() {
        channel.writeAndFlush(new PongWebSocketFrame());
    }

    public void pongMessage(String message) {
        channel.writeAndFlush(new PongWebSocketFrame(Unpooled.copiedBuffer(message, CharsetUtil.UTF_8)));
    }

    public void pongMessage(byte[] message) {
        channel.writeAndFlush(new PongWebSocketFrame(Unpooled.copiedBuffer(message)));
    }

    public void textMessage() {
        channel.writeAndFlush(new TextWebSocketFrame());
    }

    public void textMessage(String message) {
        channel.writeAndFlush(new TextWebSocketFrame(message));
    }

    public void textMessage(byte[] message) {
        channel.writeAndFlush(new TextWebSocketFrame(Unpooled.copiedBuffer(message)));
    }

    public void binaryMessage() {
        channel.writeAndFlush(new BinaryWebSocketFrame());
    }

    public void binaryMessage(byte[] message) {
        channel.writeAndFlush(new BinaryWebSocketFrame(Unpooled.copiedBuffer(message)));
    }

    public void closeMessage() {
        channel.writeAndFlush(new CloseWebSocketFrame(), channel.newPromise()).addListener(ChannelFutureListener.CLOSE);
    }

    public void closeChannel() {
        channel.close();
    }
}
